package games.ninJumpDx.ui.actions
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	import flash.utils.getTimer;
	
	import utils.Cartoon;
	
	public class MoveUnit extends Cartoon
	{
		private var m_bmd:BitmapData; // 动画素材
		private var m_des:Object;	  // 动画描述
		
		private var m_currentFrame:Number;
		private var m_offset:Dictionary;
		private var m_size:Dictionary;
		private var m_totalFrames:int;
		private var m_smoothing:Boolean;
		private var m_animations:Vector.<Object>;
		
		private var m_width:Number;
		private var m_height:Number;
		private var m_bmdCopy:BitmapData;
		private var m_bm:Bitmap;
		
		public function MoveUnit(bmd:BitmapData,des:Object)
		{
			super();
			m_bmd = bmd;
			m_des = des;
			analyseBmd();
			analyseDes();
			
		}
		
		override public function update(t:Object = null):void
		{
			if(!start || pause)return;
			var temp:Number = Math.floor((getTimer()-m_startTime) / m_animations[m_currentFrame ].duration * 0.001) % m_totalFrames;
			if(m_currentFrame == temp)return;
			m_currentFrame = temp;
			var label:String = m_animations[m_currentFrame ].frame;
			if(m_bmdCopy)m_bmdCopy.dispose();
			m_bmdCopy = new BitmapData(m_width *  m_size[label].x ,m_height *  m_size[label].y ,true,0xFFFFFF);
			m_bmdCopy.lock();
			m_bmdCopy.copyPixels(m_bmd,new Rectangle(m_offset[label].x * m_width ,m_height - m_offset[label].y * m_height - m_height * m_size[label].y, m_width *  m_size[label].x,m_height *  m_size[label].y),new Point(0,0));
			m_bmdCopy.unlock();
			m_bm = new Bitmap(m_bmdCopy);
			m_bm.smoothing = true;
			addChild(m_bm);
		}
		
		override public function destroy(e:* = null):void
		{
			super.destroy();
			m_bmd.dispose();
			if(m_bmdCopy)m_bmdCopy.dispose();
			m_des= null
			m_offset = null;
			m_size = null;
			m_animations = null;
		}
		
		private function analyseBmd():void
		{
			m_width = m_bmd.width  ;
			m_height = m_bmd.height  ;
		}
		
		private function analyseDes():void
		{
			m_currentFrame = 0;
			m_offset = new Dictionary(true);
			m_size = new Dictionary(true);
			m_totalFrames = m_des.animations[0].key_frames.length;
			m_smoothing = Boolean(m_des.animations[0].smooth);
			for(var i:int = 0; i < m_des.frames.length; i++)
			{
				m_offset[ m_des.frames[i].name] = m_des.frames[i].offset;
				m_size[ m_des.frames[i].name] = m_des.frames[i].size;
			}
			
			m_animations = new Vector.<Object>();
			for(i = 0; i < m_totalFrames; i++)
			{
				m_animations.push(m_des.animations[0].key_frames[i]);
			}
		}
	}
}